import { observable, action } from 'mobx';
import { WeaForm } from 'comsMobx';
import { WeaLocaleProvider } from 'ecCom';
import { message } from 'antd';
import * as Api from '../../apis/setting/autoClearRule';
import { ValidateForm } from './util';

const getLabel = WeaLocaleProvider.getLabel;
const initalState = {
  autoClearRuleFields: [],
  editLoading: false,
  ruleId: '',
  ruleEntity: [],
  ruleConditionInfo: {},
};
export default class RuleStore {
  @observable autoClearRuleForm = new WeaForm();
  @observable autoClearRuleFields = initalState.autoClearRuleFields;
  @observable editLoading = initalState.editLoading;
  @observable ruleId = initalState.ruleId;
  @observable ruleEntity = initalState.ruleEntity;
  @observable ruleConditionInfo = initalState.ruleConditionInfo;
  @observable loaded = false; // 异步加载

  @action setStoreState = (params) => {
    Object.keys(params).forEach((key) => {
      this[key] = params[key];
    });
  };

  @action setLoaded = (bool) => {
    this.loaded = bool;
  };

  @action clear = () => this.setStoreState(initalState);

  @action operateUserEmailRule = async (params) => {
    let res = Api.operateUserEmailRule(params);
    return res;
  };

  @action getEmailAutoClearRuleCondition = (params, callback) => {
    Api.getEmailAutoClearRuleCondition(params).then((res) => {
      const { conditioninfo, ruleconditioninfo } = res;
      this.autoClearRuleForm = new WeaForm();
      this.autoClearRuleForm.initFormFields(conditioninfo);
      this.autoClearRuleFields = conditioninfo || [];
      this.ruleConditionInfo = ruleconditioninfo.itemRule || {};
      this.getRuleEntity(params, callback);
      if (callback) callback();
    });
  };

  @action getRuleEntity = (params, callback) => {
    Api.getUserEmailAutoClearRuleEntity(params).then((res) => {
      const { emailAutoClearRuleConditionList } = res;
      this.ruleEntity = emailAutoClearRuleConditionList || [];
      if (callback) callback();
    });
  };

  @action operateUserEmailAutoClearRuleSetting = (params) => {
    ValidateForm(this.autoClearRuleForm, () => {
      let formParams = this.autoClearRuleForm.getFormParams();
      params = { ...formParams, ...params };
      Api.operateUserEmailAutoClearRule(params).then((res) => {
        if (res.flag) {
          message.success(getLabel(384443, '更新设置成功'));
        } else {
          message.error(getLabel(384444, '更新设置失败'));
        }
      });
    });
  };
}
